<template>
	<view class="uv-page" style="background-color: #fff;">
		<view class="uv-demo-block">
			<view class="uv-demo-block__content">
				<uv-form :model="form" :rules="rules" ref="form1" labelWidth="auto">

					<uv-form-item prop="roomName" required label="房间:" borderBottom @click="showRoomSelect">
						<uv-input v-model="form.roomName" disabled disabledColor="#ffffff" placeholder="请选择房间"
							border="none"></uv-input>
						<template v-slot:right>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-form-item>

					<uv-form-item prop="writeDate" required label="日期:" borderBottom @click="writeDateOpen">
						<uv-input v-model="form.writeDate" disabled disabledColor="#ffffff" placeholder="请选择日期"
							border="none"></uv-input>
						<template v-slot:right>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-form-item>
					<uv-form-item prop="timeSlot" required label="类型:" borderBottom>
						<uv-radio-group v-model="form.timeSlot">
							<uv-radio name="0" label="午市" key="0"></uv-radio>
							<uv-radio name="1" label="晚市" key="1"></uv-radio>
						</uv-radio-group>
					</uv-form-item>
					<uv-form-item prop="items" label="菜品:" borderBottom>
						<uv-upload :fileList="fileList1" name="1" multiple :maxCount="10" @afterRead="afterRead"
							@delete="deletePic"></uv-upload>
					</uv-form-item>
					<uv-form-item prop="booker" label="订台:" borderBottom @click="showBookerSelect">
						<uv-input v-model="form.booker" disabled disabledColor="#ffffff" placeholder="请选择订台"
							border="none"></uv-input>
						<template v-slot:right>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-form-item>
					<uv-form-item prop="standAttendant" label="看台:" borderBottom @click="showStandAttendantSelect">
						<uv-input v-model="form.standAttendant" disabled disabledColor="#ffffff" placeholder="请选择看台"
							border="none"></uv-input>
						<template v-slot:right>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-form-item>

					<uv-form-item prop="eatNum" label="用餐人数:" borderBottom>
						<uv-input v-model="form.eatNum" type="number" border="none" placeholder="请输入用餐人数"></uv-input>
					</uv-form-item>
					<uv-form-item prop="guestName" label="贵宾姓名:" borderBottom>
						<uv-input v-model="form.guestName" border="none" placeholder="请填写贵宾姓名"></uv-input>
					</uv-form-item>
					<uv-form-item prop="sex" label="性别:" borderBottom>
						<uv-radio-group v-model="form.sex">
							<uv-radio :name="1" label="男" key="1"></uv-radio>
							<uv-radio :name="2" label="女" key="2"></uv-radio>
							<uv-radio :name="-1" label="未知" key="0"></uv-radio>
						</uv-radio-group>
					</uv-form-item>
					<uv-form-item prop="contact" label="电话:" borderBottom>
						<uv-input v-model="form.contact" border="none" placeholder="请输入电话"></uv-input>
					</uv-form-item>
					<uv-form-item prop="entertain" label="宴请性质:" borderBottom>
						<!-- 宴请性质：商务宴请，家庭聚餐，朋友聚餐，生日宴会，其他 -->
						<uv-radio-group v-model="form.entertain">
							<uv-radio :name="1" label="商务宴请" key="1"></uv-radio>
							<uv-radio :name="2" label="家庭聚餐" key="2"></uv-radio>
							<uv-radio :name="3" label="朋友聚餐" key="3"></uv-radio>
							<uv-radio :name="4" label="生日宴会" key="4"></uv-radio>
							<uv-radio :name="5" label="其他" key="5"></uv-radio>
						</uv-radio-group>
					</uv-form-item>
					<uv-form-item prop="guestType" label="客人类型:" borderBottom>
						<uv-radio-group v-model="form.guestType">
							<uv-radio :name="0" label="优质" key="0"></uv-radio>
							<uv-radio :name="1" label="潜在" key="1"></uv-radio>
							<uv-radio :name="2" label="低频" key="2"></uv-radio>
						</uv-radio-group>
					</uv-form-item>
					<uv-form-item prop="amount" label="消费金额:" borderBottom>
						<uv-input v-model="form.amount" type="number" border="none" placeholder="请输入消费金额"></uv-input>
					</uv-form-item>

					<uv-form-item prop="paymentMethod" label="结账方式:" borderBottom>
						<uv-radio-group v-model="form.paymentMethod">
							<uv-radio :name="0" label="会员卡"></uv-radio>
							<uv-radio :name="1" label="现金"></uv-radio>
							<uv-radio :name="2" label="挂账"></uv-radio>
						</uv-radio-group>
					</uv-form-item>

					<uv-form-item prop="preference" label="禁忌、喜好:" borderBottom>
						<uv-textarea v-model="form.preference" placeholder="请输入禁忌、喜好"></uv-textarea>
					</uv-form-item>
					<uv-form-item prop="comments" label="意见、建议:" borderBottom>
						<uv-textarea v-model="form.comments" placeholder="请输入意见、建议"></uv-textarea>
					</uv-form-item>
				</uv-form>

				<uv-button type="primary" text="提交" customStyle="margin-top: 10px" @click="submit"
					v-if="editFlag"></uv-button>
				<view>
					<!-- 选择填单日期 -->
					<uv-datetime-picker ref="writeDatePicker" v-model="writeDate" mode="date"
						@confirm="writeDateConfirm"></uv-datetime-picker>

					<!-- 选择房间号 -->
					<uv-picker ref="roomSelect" :columns="rooms" @confirm="roomSelect" keyName="title"></uv-picker>

					<!-- 选择订台 -->
					<uv-picker ref="bookerSelect" :columns="bookerData" @confirm="bookerSelect"
						keyName="realName"></uv-picker>

					<!-- 选择看台 -->
					<uv-picker ref="standAttendantSelect" :columns="standAttendantData" @confirm="standAttendantSelect"
						keyName="realName"></uv-picker>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		timeFormat
	} from '@climblee/uv-ui/libs/function/index.js';
	import CustomerAPI from '@/api/customer'
	import AreaAPI from "@/api/area";
	import UploadAPI from '@/api/upload';
	import CommonAPI from "@/api/common";
	import {
		isToday
	} from "@/utils/media";

	export default {
		data() {
			return {
				id: '',
				fileList1: [], // 上传的图片
				form: {
					roomName: '',
					writeDate: '',
					timeSlot: '',
					items: '',
					booker: '',
					standAttendant: '',
					orderingPeople: '',
					eatNum: '',
					guestName: '',
					contact: '',
					entertain: '',
					arrivalTime: '',
					departureTime: '',
					guestType: '',
					amount: '',
					paymentMethod: '',
					servingTime: '',
					preference: '',
					comments: '',
					roomId: ''
				},

				rules: {
					roomId: {
						required: true,
						message: '请输入房间',
						trigger: ['blur']
					},
					writeDate: {
						required: true,
						message: '请输入填单日期',
						trigger: ['change']
					},
					timeSlot: {
						required: true,
						message: '请输入类型(午市 晚市)',
						trigger: ['change']
					}
				},

				rooms: [], // 房间
				writeDate: Number(new Date()), //填单日期
				bookerData: [],
				standAttendantData: [],
				editFlag: true //默认允许编辑提交

			}
		},
		onShow() {
			this.getRooms()
			this.getUserList()
		},
		onLoad(e) {
			this.id = e.id
			if (this.id) {
				this.detail(this.id)
			}
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.form1.setRules(this.rules)
		},
		methods: {
			detail() {
				CustomerAPI.customerDetail({
					id: this.id
				}).then(res => {
					console.log(res.data);
					this.form = res.data
					// 判断是否可以编辑 如果是今天，可以编辑
					this.editFlag = isToday(this.form.createTime)
					// 菜品图片
					if (this.form.items !== '') {
						this.fileList1 = this.form.items?.split(',').map(i => {
							return {
								url: i
							}
						})
					}
				})
			},
			getUserList() {
				CommonAPI.userListByBooker().then(res => {
					if (res.code !== 200) {
						return
					}
					this.bookerData = [
						[...res.data]
					]
				})
				CommonAPI.userListByStand().then(res => {
					if (res.code !== 200) {
						return
					}
					this.standAttendantData = [
						[...res.data]
					]
				})
			},
			getRooms() {
				AreaAPI.tree(2).then(res => {
					if (res.code !== 200) {
						return
					}
					this.rooms = [
						[...res.data]
					]
				})
			},
			// 提交
			submit() {
				this.form.items = this.fileList1.map(i => i.url).join(',')
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				this.$refs.form1.validate().then(res => {
					CustomerAPI.customerSubmit(this.form).then(res => {
						if (res.code === 200) {
							uni.showToast({
								icon: 'success',
								title: '提交成功'
							})
						}
						// 返回客情列表
						uni.reLaunch({
							url: '/subpackage/customer/customer'
						})
					})
				}).catch(errors => {
					uni.showToast({
						icon: 'error',
						title: '校验失败'
					})
				})
			},
			// 重置
			reset() {
				const validateList = ['roomName', 'writeDate', 'timeSlot', 'items', 'booker', 'standAttendant',
					'orderingPeople', 'eatNum', 'guestName', 'contact', 'entertain', 'guestName', 'arrivalTime',
					'departureTime', 'guestType', 'amount', 'preparation', 'paymentMethod', 'firstDishTime',
					'servingTime', 'preference', 'comments'
				]
				this.$refs.form1.resetFields()
				this.$refs.form1.clearValidate()
				setTimeout(() => {
					this.$refs.form1.clearValidate(validateList)
					// 或者使用 this.$refs.form1.clearValidate()
				}, 10)
			},
			// 房间选择
			showRoomSelect() {
				this.$refs.roomSelect.open();
			},
			// 房间选择返回结果
			roomSelect(e) {
				console.log('选中该项：', e);
				this.form.roomName = e.value[0].title;
				this.form.roomId = e.value[0].id;
				// 对部分表单字段进行校验
				this.$refs.form1.validateField('roomName', err => {
					// 处理错误后的逻辑
				})
			},
			// 订台选择
			showBookerSelect() {
				this.$refs.bookerSelect.open();
			},
			bookerSelect(e) {
				console.log('选中该项：', e);
				this.form.booker = e.value[0].realName;
			},

			// 服务员选择
			showStandAttendantSelect() {
				this.$refs.standAttendantSelect.open();
			},
			standAttendantSelect(e) {
				console.log('选中该项：', e);
				this.form.standAttendant = e.value[0].realName;
			},

			writeDateOpen() {
				this.$refs.writeDatePicker.open();
			},
			writeDateConfirm(e) {
				console.info(e)
				this.form.writeDate = timeFormat(e.value, 'yyyy-mm-dd')
			},

			hideKeyboard() {
				uni.hideKeyboard()
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				console.info(event)
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			async uploadFilePromise(url) {
				let data = await UploadAPI.uploadFile(url)
				return data.link
			}
		}
	}
</script>
<style lang="scss" scoped>
	.uv-page {
		padding: 15px 15px 40px 15px;
	}

	.uv-demo-block {
		margin-bottom: 22px;
	}

	.uv-demo-block__title {
		font-size: 14px;
		color: #8f9ca2;
		margin-bottom: 8px;
	}

	.uv-demo-block__title {
		font-size: 14px;
		color: #8f9ca2;
		margin-bottom: 8px;
	}

	.uv-demo-block__content {
		flex-direction: row;
		flex-wrap: wrap;
		align-items: center;
	}
</style>